package com.gzhryc.net_marketing.cloud.micro.api.controllers.v1;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApply;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApplyMember;
import com.gzhryc.net_marketing.cloud.business.dao.enums.PayGoodsOrderEnum;
import com.gzhryc.net_marketing.cloud.business.dao.enums.TeamPayApplyMemberEnum;
import com.gzhryc.net_marketing.cloud.business.services.TeamPayApplyMemberService;
import com.gzhryc.net_marketing.cloud.business.services.TeamPayApplyService;
import com.gzhryc.net_marketing.cloud.business.services.dto.TeamPayApplyMemberSearch;
import com.gzhryc.net_marketing.cloud.micro.api.ClientAPICodeConstants;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.order.MemberOrderInfoRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.order.MemberOrderInfoResponse;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.order.MemberOrderListRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.order.MemberOrderListResponse;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.team.TeamPayGetApplyInfoRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.team.TeamPayGetApplyInfoResponse;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;

public class MarketTeamPayOrderController {

	@Route(value = { "/member/market/team_pay/order/list.data" })
    public MemberOrderListResponse orderList(HttpServletRequest request) {
        MemberOrderListResponse apiResp = new MemberOrderListResponse(ClientAPICodeConstants.NULL_DATA);
        MemberOrderListRequest apiReq = WebUtils.getJsonRequest(request, MemberOrderListRequest.class);
        if (apiReq != null && apiReq.getBody().getState() != null) {
        	LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
            if (loginMember != null) {
                TeamPayApplyMemberSearch search = new TeamPayApplyMemberSearch();
                search.setMemberId(loginMember.getId());
                if (apiReq.getBody().getState() == 1) {
                    search.setState(TeamPayApplyMemberEnum.State.Waiting.index());
                } else if (apiReq.getBody().getState() == 2) {
                    search.setState(TeamPayApplyMemberEnum.State.Participating.index());
                } else if (apiReq.getBody().getState() == 3) {
                    search.setState(TeamPayApplyMemberEnum.State.Finish.index());
                } else if (apiReq.getBody().getState() == 4) { //等待评价
                    search.setState(TeamPayApplyMemberEnum.State.Drain.index());
                }

                List<TeamPayApplyMember> data = TeamPayApplyMemberService.self().findBySearch(search, apiReq.getBody().getPageNo(),
                        apiReq.getBody().getPageLimit());
                if (data != null && data.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS);
                    for (TeamPayApplyMember applyMember : data) {
                        MemberOrderListResponse.Item item = new MemberOrderListResponse.Item();
                        item.setTradeNo(applyMember.getPayTradeNo());
                        item.setGoodsId(applyMember.getGoodsId());
                        item.setGoodsName(applyMember.getGoodsName());
                        item.setGoodsTypeNames(applyMember.getGoodsTypeNames());
                        item.setGoodsSpaceName(applyMember.getGoodsSpaceName());

                        item.setGoodsImg(applyMember.getGoodsImg());
                        if (StringUtils.isNotBlank(applyMember.getGoodsImg())) {
                            if (!applyMember.getGoodsImg().startsWith("http")) {
                        		String resDomain = PropertyTools.get().getString("marketResDomain");
                                item.setGoodsImg(resDomain + applyMember.getGoodsImg());
                            }
                        }
                        item.setGoodsMoney(applyMember.getGoodsMoneyStr());
                        item.setPayMoney(applyMember.getPayMoneyStr());
                        item.setState(applyMember.getState());
                        item.setStateName(applyMember.getStateName());
                        item.setGoodsCount(applyMember.getGoodsCount());
                        item.setCreateDate(DateFormatUtils.format(applyMember.getCreateDate(), "yyyy-MM-dd HH:mm"));
                        item.setApplyId(applyMember.getApplyId());
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/member/market/team_pay/order/info.data" })
    public MemberOrderInfoResponse orderInfo(HttpServletRequest request) {
        MemberOrderInfoResponse apiResp = new MemberOrderInfoResponse(ClientAPICodeConstants.EXECUTE_ERROR, "获取订单失败，请稍后再试");
        MemberOrderInfoRequest apiReq = WebUtils.getJsonRequest(request, MemberOrderInfoRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo())) {
        	LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
            if (loginMember != null) {
                TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().getByPayTradeNo(apiReq.getBody().getTradeNo());
                if (applyMember != null) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setTradeNo(applyMember.getPayTradeNo());
                    apiResp.getBody().setBusinessType(PayGoodsOrderEnum.BusinessType.TeamPay.index());
                    apiResp.getBody().setGoodsId(applyMember.getGoodsId());
                    apiResp.getBody().setGoodsName(applyMember.getGoodsName());

                    apiResp.getBody().setGoodsImg(applyMember.getGoodsImg());
                    if (StringUtils.isNotBlank(applyMember.getGoodsImg())) {
                        if (!applyMember.getGoodsImg().startsWith("http")) {
                    		String resDomain = PropertyTools.get().getString("marketResDomain");
                            apiResp.getBody().setGoodsImg(resDomain + applyMember.getGoodsImg());
                        }
                    }
                    apiResp.getBody().setGoodsMoney(applyMember.getGoodsMoneyStr());
                    apiResp.getBody().setGoodsCount(applyMember.getGoodsCount());
                    apiResp.getBody().setGoodsSpaceName(applyMember.getGoodsSpaceName());
                    apiResp.getBody().setPayMoney(applyMember.getPayMoneyStr());
                    apiResp.getBody().setLogisticsMoney(applyMember.getLogisticsMoneyStr());
                    apiResp.getBody().setCouponMoney("0");
                    apiResp.getBody().setRewardMoney(applyMember.getRewardMoneyStr());
                    apiResp.getBody().setState(applyMember.getState());
                    apiResp.getBody().setPayType(applyMember.getPayType());
                    apiResp.getBody().setPayTypeName(applyMember.getPayTypeName());
                    apiResp.getBody().setCreateDate(DateFormatUtils.format(applyMember.getCreateDate(), "yyyy-MM-dd HH:mm"));
                    // 团拼信息
                    TeamPayApply applyEntity = TeamPayApplyService.self().getById(applyMember.getApplyId());
                    if (applyEntity != null) {
                        MemberOrderInfoResponse.TeamPayInfo teamPayInfo = new MemberOrderInfoResponse.TeamPayInfo();
                        teamPayInfo.setApplyId(applyEntity.getId());
                        teamPayInfo.setTeamMemberTotal(applyEntity.getTeamMemberTotal());
                        teamPayInfo.setState(applyEntity.getState());

                        List<TeamPayApplyMember> applyMemberList = TeamPayApplyMemberService.self().findByApplyId(applyMember.getApplyId());
                        if (applyMemberList != null && applyMemberList.size() > 0) {
                            for (TeamPayApplyMember applyMemberItem : applyMemberList) {
                                MemberOrderInfoResponse.TeamPayInfoMember item = new MemberOrderInfoResponse.TeamPayInfoMember();
                                item.setMemberId(applyMemberItem.getMemberId());
                                item.setNickname(applyMemberItem.getMemberNickname());
                                item.setFaceImg(applyMemberItem.getMemberFaceImg());
                                item.setType(applyMemberItem.getRoleType());
                                teamPayInfo.getMembers().add(item);
                            }
                        }
                        apiResp.getBody().setTeamPayInfo(teamPayInfo);
                    }
                    // 收货地址
                    if (applyMember.getMailAddressId() != null) {
                        MemberOrderInfoResponse.MailAddress mailAddress = new MemberOrderInfoResponse.MailAddress();
                        mailAddress.setId(applyMember.getMailAddressId());
                        mailAddress.setReceiveName(applyMember.getReceiveName());
                        mailAddress.setReceivePhone(applyMember.getReceivePhone());
                        mailAddress.setReceiveAddress(applyMember.getReceiveAddress());
                        apiResp.getBody().setMailAddress(mailAddress);
                    }
                }
            }
        }
        return apiResp;
    }
    
    /**
	 * 获取最新的团拼信息
	 * @return
	 */
	@Route(value = { "/member/market/team_pay/order/new.data" })
	public TeamPayGetApplyInfoResponse getNew(HttpServletRequest request){
		TeamPayGetApplyInfoResponse apiResp = new TeamPayGetApplyInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
		TeamPayApply applyEntity = TeamPayApplyService.self().getByNew();
		if(applyEntity != null) {
			apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
			apiResp.getBody().setApplyId(applyEntity.getId());
			apiResp.getBody().setState(applyEntity.getState());
			apiResp.getBody().setGoodsId(applyEntity.getGoodsId());
			apiResp.getBody().setTeamMemberTotal(applyEntity.getTeamMemberTotal());
			apiResp.getBody().setTeamMemberCount(applyEntity.getTeamMemberCount());
			apiResp.getBody().setGainCount(applyEntity.getTeamGainCount());
			apiResp.getBody().setStartDate(DateFormatUtils.format(applyEntity.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
			apiResp.getBody().setEndDate(DateFormatUtils.format(applyEntity.getEndDate(), "yyyy-MM-dd HH:mm:ss"));
			apiResp.getBody().setTimes((applyEntity.getEndDate().getTime() - System.currentTimeMillis()));
			apiResp.getBody().setAttendState(0);    //默认没有参加

			Member member = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, Member.class);
			List<TeamPayApplyMember> applyMemberList = TeamPayApplyMemberService.self().findByApplyId(applyEntity.getId());
			if (applyMemberList != null && applyMemberList.size() > 0) {
				for (TeamPayApplyMember applyMember : applyMemberList) {
					TeamPayGetApplyInfoResponse.MemberItem item = new TeamPayGetApplyInfoResponse.MemberItem();
					item.setMemberId(applyMember.getMemberId());
					item.setNickname(applyMember.getMemberNickname());
					item.setFaceImg(applyMember.getMemberFaceImg());
					if (applyMember.getMemberId().equals(applyEntity.getMemberId())) {
						item.setType(1);
					} else {
						item.setType(2);
					}
					if (member != null && member.getId().equals(item.getMemberId())) {
						apiResp.getBody().setAttendState(1);    //代表参加了
					}
					apiResp.getBody().getMembers().add(item);
				}
			}
		}
		return apiResp;
	}

    /**
	 * 获取团拼详情
	 * 
	 * @param request
	 * @return
	 */
	@Route(value = { "/member/market/team_pay/order/apply/info.data" })
	public TeamPayGetApplyInfoResponse getApply(HttpServletRequest request) {
		TeamPayGetApplyInfoResponse apiResp = new TeamPayGetApplyInfoResponse(ClientAPICodeConstants.NULL_DATA, "无用户团拼信息");
		TeamPayGetApplyInfoRequest apiReq = WebUtils.getJsonRequest(request, TeamPayGetApplyInfoRequest.class);
		if (apiReq != null && (apiReq.getBody().getGoodsId() != null || apiReq.getBody().getApplyId() != null)) {
			LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
			
			TeamPayApply applyEntity = null;
			if (apiReq.getBody().getApplyId() != null) {
				applyEntity = TeamPayApplyService.self().getById(apiReq.getBody().getApplyId());
			} else if (apiReq.getBody().getGoodsId() != null) {
				if (loginMember != null) {
					applyEntity = TeamPayApplyService.self().getJoinByGoodsIdAndMemberId(apiReq.getBody().getGoodsId(), loginMember.getId());
				}
			}

			if (applyEntity != null) {
				List<TeamPayApplyMember> applyMemberList = TeamPayApplyMemberService.self().findByApplyId(applyEntity.getId());
				if (applyMemberList != null && applyMemberList.size() > 0) {
					apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
					apiResp.getBody().setApplyId(applyEntity.getId());
					apiResp.getBody().setState(applyEntity.getState());
					apiResp.getBody().setGoodsId(applyEntity.getGoodsId());
					apiResp.getBody().setTeamMemberTotal(applyEntity.getTeamMemberTotal());
					apiResp.getBody().setTeamMemberCount(applyEntity.getTeamMemberCount());
					apiResp.getBody().setGainCount(applyEntity.getTeamGainCount());
					apiResp.getBody().setStartDate(DateFormatUtils.format(applyEntity.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
					apiResp.getBody().setEndDate(DateFormatUtils.format(applyEntity.getEndDate(), "yyyy-MM-dd HH:mm:ss"));
					apiResp.getBody().setTimes((applyEntity.getEndDate().getTime() - System.currentTimeMillis()));
					apiResp.getBody().setAttendState(0);    //默认没有参加
					for (TeamPayApplyMember applyMember : applyMemberList) {
						TeamPayGetApplyInfoResponse.MemberItem item = new TeamPayGetApplyInfoResponse.MemberItem();
						item.setMemberId(applyMember.getMemberId());
						item.setNickname(applyMember.getMemberNickname());
						item.setFaceImg(applyMember.getMemberFaceImg());
						if (applyMember.getMemberId().equals(applyEntity.getMemberId())) {
							item.setType(1);
						} else {
							item.setType(2);
						}
						if (loginMember != null && loginMember.getId().equals(item.getMemberId())) {
							apiResp.getBody().setAttendState(1);    //代表参加了
						}
						apiResp.getBody().getMembers().add(item);
					}
				}
			}
		}
		return apiResp;
	}
}
